package com.xxd.dfs.datanode;

import com.xxd.dfs.namenode.rpc.model.HeartbeatResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: XiaoDong.Xie
 * @create: 2020-08-24 12:19
 * @description: 心跳发送组件
 */
public class HeartbeatManager {

    private final Logger logger = LoggerFactory.getLogger(HeartbeatManager.class);
    private Long HEARTBEAT_INTERVAL = Long.parseLong(Config.getInstance().get("heartbeat.interval"));
    private NameNodeRpcClient namenodeRpcClient;

    public HeartbeatManager(NameNodeRpcClient namenodeRpcClient) {
        this.namenodeRpcClient = namenodeRpcClient;
    }

    public void start() {
        new HeartbeatThread().start();
    }
    /**
     * 负责心跳的线程
     */
    class HeartbeatThread extends Thread {

        @Override
        public void run() {
            while (true) {
                logger.info("发送 rpc 请求 给NameNode 进行心跳....");
                // 通过RPC接口发送到NameNode他的注册接口上去
                HeartbeatResponse response = namenodeRpcClient.heartbeat();
                logger.info("心跳请求的结果为 {} ", response.getStatus());

                try {
                    Thread.sleep(HEARTBEAT_INTERVAL);
                } catch (Exception e) {
                    logger.error("error", e);
                }
            }
        }
    }
}
